import { TMakeCompiler } from './compiler';
import { BuiltInFunction, ExtensionFunction, FunctionParameter } from './types';
import { PluginSystem } from './plugin-system';
import * as fs from 'fs';
import * as path from 'path';

/**
 * 函数描述接口，用于VSCode插件的补全文件
 */
export interface VSCodeFunctionDescription {
  name: string;
  description: string;
  params: {
    name: string;
    type: string;
    required: boolean;
    description: string;
  }[];
  plugin?: string; // 新增：标识函数所属的插件
}

/**
 * 生成函数描述数据的类
 */
export class FunctionDescriptionGenerator {
  /**
   * 从编译器实例生成所有函数的描述数据
   * @param compiler TMakeCompiler实例
   * @param pluginSystem 可选的插件系统实例，用于获取插件函数信息
   * @returns 函数描述数组
   */
  public static generateFromCompiler(compiler: TMakeCompiler, pluginSystem?: PluginSystem): VSCodeFunctionDescription[] {
    const functionsMap = this.getFunctionsMap(compiler);
    
    // 获取插件系统中的函数信息
    const pluginFunctionsMap = new Map<string, string>();
    if (pluginSystem) {
      const pluginFunctions = pluginSystem.getRegisteredFunctions();
      for (const func of pluginFunctions) {
        pluginFunctionsMap.set(func.name, func.plugin);
      }
    }
    
    const functionDescriptions: VSCodeFunctionDescription[] = [];
    
    functionsMap.forEach((func, name) => {
      const description: VSCodeFunctionDescription = {
        name: name,
        description: func.description || `函数 ${name}`,
        params: [],
        plugin: pluginFunctionsMap.get(name) // 插件信息
      };
      
      // 转换参数描述
      if (func.parameters && func.parameters.length > 0) {
        description.params = func.parameters.map((param: FunctionParameter) => ({
          name: param.name,
          type: param.type || 'any',
          required: param.required !== false,
          description: param.description || ''
        }));
      }
      
      functionDescriptions.push(description);
    });
    
    return functionDescriptions;
  }
  
  /**
   * 获取编译器的functions映射
   */
  private static getFunctionsMap(compiler: TMakeCompiler): Map<string, BuiltInFunction | ExtensionFunction> {
    const compilerWithPublicFunctions = compiler as any;
    return compilerWithPublicFunctions.functions || new Map();
  }
  
  /**
   * 将函数描述数组写入JSON文件
   * @param functions 函数描述数组
   * @param outputPath 输出文件路径
   */
  public static writeToFile(functions: VSCodeFunctionDescription[], outputPath: string): void {
    const data = {
      functions: functions
    };
    
    // 确保目录存在
    const dir = path.dirname(outputPath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
    
    // 写入文件
    fs.writeFileSync(outputPath, JSON.stringify(data, null, 2), 'utf-8');
    console.log(`函数描述文件已生成: ${outputPath}`);
  }
}